import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:hk_base/hk_base.dart';

typedef EnsureClickCallBack = void Function(bool isBlock);

class AppRouterModel {
  /// 当前路由
  final String current;

  /// 参数
  final dynamic arguments;

  /// 初始化
  AppRouterModel(this.current, this.arguments);
}

class AppRouterService extends GetxService {
  /// 保存路由信息
  List<AppRouterModel> routers = [];

  /// 创建
  static AppRouterService _createService() {
    if (Get.isRegistered<AppRouterService>()) {
      return Get.find<AppRouterService>();
    }
    return Get.put(AppRouterService());
  }

  /// 获取单例
  static AppRouterService get _service => _createService();

  /// 确保路由栈中只存在一个页面
  static Future<T?>? toSingleName<T>(String page,
      {dynamic arguments, EnsureClickCallBack? callBack}) async {
    /// 检查当前页面是否存在在路由栈中
    final router = _service.routers
        .firstWhereOrNull((e) => e.current == page && e.arguments == arguments);

    /// 不存在则保存跳转
    if (router == null) {
      HkLog.d("router--add---------$page----------------${Get.currentRoute}");
      _service.routers.add(AppRouterModel(page, arguments));
      return Get.toNamed(page, arguments: arguments, preventDuplicates: false)
          ?.then((value) {
        if (callBack != null) callBack(value["isBlock"]);
      });
    }
    Get.until((route) =>
        route.settings.name == router.current &&
        route.settings.arguments == router.arguments);
    return null;
  }

  /// 检查指定路由是否可以移除
  static Future<void> checkRemoveRoute(Route? route) async {
    if (route == null) return;

    /// 要退出的页面
    final routePage = route.settings.name ?? "";

    /// 要退出页面的参数
    final argument = route.settings.arguments;

    /// 获取退出路由
    final pageRoute = _service.routers.firstWhereOrNull(
        (e) => e.current == routePage && e.arguments == argument);

    /// 检查路由 存在则移除
    if (pageRoute != null) _service.routers.remove(pageRoute);
  }
}

class AppRouterObserver extends NavigatorObserver {
  @override
  void didPop(Route route, Route? previousRoute) {
    AppRouterService.checkRemoveRoute(route);
    super.didPop(route, previousRoute);
    HkLog.d(
        "router--didPop---${previousRoute?.settings.name}--current-${route.settings.name}");
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    HkLog.d(
        "router--didPush---${previousRoute?.settings.name}--current---${route.settings.name}");
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    AppRouterService.checkRemoveRoute(route);
    super.didRemove(route, previousRoute);
    HkLog.d(
        "router--didRemove---${previousRoute?.settings.name}--current--${route.settings.name}");
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    HkLog.d(
        "router--didReplace---${oldRoute?.settings.name}--new--${newRoute?.settings.name}");
  }
}
